package com.fkframe.codegener.ui.view;

import heip.generator.entity.ColumnClazz;
import heip.generator.entity.EntityTable;
import heip.generator.entity.PropEditor;
import heip.generator.entity.PropEditor.EditType;
import heip.generator.entity.TableClazz;
import heip.generator.entity.ValidateRule;
import heip.generator.entity.ValidateRule.ValidateType;
import heip.generator.generer.ActionGenerator;
import heip.generator.generer.EntityGenerator;
import heip.generator.generer.FlexGenerator;
import heip.generator.generer.ServiceDaoGenerator;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import cn.org.rapid_framework.generator.GeneratorProperties;

import com.fkframe.codegener.ui.EETSoftFrame;

/**
 * 单表生成机制
 * 
 * @author AGUU
 * 
 */
public class SingleGenerView extends CommonView {
	private JTextField txtModule;
	private JTextField txtTable;
	private JComboBox entityType;
	private JCheckBox chkPageable;
	private EETSoftFrame parentFrame;

	private JButton btnLoad;
	private JButton btnTree;
	private JButton btnGener;
	private JPanel panel;
	private JPanel mainPanel;
	private JViewport jViewport;
	private JTable table;
	
	JScrollPane scrollPane;
	public SingleGenerView(EETSoftFrame parent, JPanel mainPanel,JViewport jViewport) {
		this.parentFrame = parent;
		this.mainPanel = mainPanel;
		this.jViewport = jViewport;
		
		mainPanel.setPreferredSize(new Dimension(parentFrame.getMinMainBoardWidth(), 500));
		mainPanel.removeAll();
		mainPanel.repaint();
		
		/*JPanel fr5 = new JPanel();
		64     fr5.setBorder(new TitledBorder("BoxLayout - Y"));
		65     fr5.setLayout(new BoxLayout(fr5, BoxLayout.Y_AXIS));
		66     fr5.add(new JButton("1"));
		67     fr5.add(Box.createVerticalStrut(10));
		68     fr5.add(new JButton("2"));
		69     fr5.add(Box.createGlue());
		70     fr5.add(new JButton("3"));
		71     fr5.add(Box.createVerticalGlue());
		72     fr5.add(new JButton("4"));
		73     desktop.add(fr5, 0);*/
		
		setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
		//setLayout(new FlowLayout(FlowLayout.CENTER, 1, 1));
		//this.mainPanel.setSize(700, 500);
		panel = new JPanel();
		panel.setLayout(new FlowLayout(FlowLayout.CENTER, 1, 1));
		
		JPanel panel_2 = new JPanel();
		panel_2.setLayout(new GridLayout(0, 4, 10, 10));
		
		//模块
		panel_2.add(new JLabel("模块名(ex:cm.tb):"));
		txtModule = new JTextField();
		txtModule.setColumns(10);
		panel_2.add(txtModule);

		//表名
		panel_2.add(new JLabel("表名(必输):"));

		txtTable = new JTextField();
		panel_2.add(txtTable);
		txtTable.setColumns(10);
		
		panel_2.add(new JLabel("单表类型 :"));
		entityType = new JComboBox(new Object[]{"基本"});
		panel_2.add(entityType);
		
		chkPageable = new JCheckBox("是否分页",true);
		panel_2.add(chkPageable);
		
			
		panel.add(panel_2);
		add(panel);
		add(Box.createVerticalStrut(10));
		
		panel_2.add(new JLabel(""));
		
		JButton btnNewButton = new JButton("1)加载表");
		panel_2.add(btnNewButton);
		btnNewButton.addActionListener(this);

		btnLoad = new JButton("2)生成");
		panel_2.add(btnLoad);
		btnLoad.addActionListener(this);
		
		/*btnTree = new JButton("生成树形界面");
		panel_2.add(btnTree);
		btnTree.addActionListener(this);
		*/
		//表格的界面
		
		/*
		 * for(int i=3;i<vcol.size();i++){ TableColumn aColumn =
		 * table.getColumnModel().getColumn(i);
		 * aColumn.setCellEditor(table.getDefaultEditor(Boolean.class));
		 * aColumn.setCellRenderer(table.getDefaultRenderer(Boolean.class)); }
		 */

		table = renderColumnEditTable();
		scrollPane = new JScrollPane();
		scrollPane.setViewportView(table);
		scrollPane.setSize(600, 400);
		add(scrollPane);

	}
	private TableClazz tableClazz ;
	
	
	
	public void reloadColumnPanel2() {
		// 刷新数据代码
		// 定义Vector 类型变量tmprow，colVec，并且赋值，就象上面那样，这里不重复了
		SimplePropTableModel  model= (SimplePropTableModel) table.getModel();

		String tableName = txtTable.getText();
		tableClazz = new TableClazz(tableName);
		int columnSize = tableClazz.getColumns().size();

		List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
		for (int i = 0; i < columnSize; i++) {
			ColumnClazz col = tableClazz.getColumns().get(i);
			//忽略掉ID
			if(col.isPk())continue;
			
			
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("seq", i+1);
			map.put("name",col.getName());
			map.put("cnName", col.getCnName());
			
			map.put("isQuery", false);
			map.put("isTable", true);
			map.put("isEdit", true);
			if(col.getJavaType().equals("Long")&&(col.getColumnName().indexOf("Id")!=-1)){
				map.put("editType", EditType.DIALOG.getName());
				//map.put("editRule", "");
			}else if(col.getColumnName().equals("remark")){
				map.put("editType",EditType.TEXTAREA.getName());
			}else if(col.getJavaType().equals("Date")){
				map.put("editType",EditType.DATE.getName());
			}else{
				map.put("editType", EditType.TEXTINPUT.getName());
				//map.put("editRule", "");
			}
			
			map.put("validateType1","");
			map.put("validateRule1", "");
			
			/*map.put("validateType2","");
			map.put("validateRule2", "");*/
			
			//map.put("validateType3","");
			//map.put("validateRule3", "");
			
			data.add(map);
		}
		model.setData(data);
		table.setModel(model);
		
		
		//table.validate();
		//table.repaint();
		SwingUtilities.updateComponentTreeUI(table);
	}

	/*public void reloadColumnPanel() {
		// colPane.setPreferredSize(new Dimension(600 ,500));

		mainPanel.setPreferredSize(new Dimension(parentFrame
				.getMinMainBoardWidth(), 500));
		mainPanel.removeAll();
		mainPanel.repaint();

		String tableName = txtTable.getText();
		TableClazz tableClazz = new TableClazz(tableName);
		int columnSize = tableClazz.getColumns().size();

		Vector<Vector<String>> vrow = new Vector<Vector<String>>();

		for (int i = 1; i <= columnSize; i++) {
			Vector<String> temp = new Vector<String>();
			ColumnClazz col = tableClazz.getColumns().get(i - 1);
			temp.addElement(i + "");
			temp.addElement(col.getPropName());
			temp.addElement(col.getPropCnName());
			temp.addElement("1");
			temp.addElement("1");
			temp.addElement("true");
			temp.addElement("true");
			temp.addElement("true");

			vrow.add(temp);
		}

		// JTable friends = new JTable (vrow,vcol);
		// friends.setPreferredScrollableViewportSize(new Dimension(600,
		// 100));//设置表格的大小
		JTable jTable = new JTable(vrow, vcol);

		jTable.setAutoscrolls(true);
		jTable.setFocusable(false);
		jTable.setColumnSelectionAllowed(false);

		// jTable.setRowSelectionAllowed(false);
		jTable.setRowHeight(22);
		jTable.setAutoResizeMode(0);
		// friends.setRowHeight (30);//设置每行的高度为20
		// friends.setRowHeight (0, 20);//设置第1行的高度为15
		// friends.setRowMargin (5);//设置相邻两行单元格的距离
		// friends.setRowSelectionAllowed (true);//设置可否被选择.默认为false
		// friends.setSelectionBackground (Color.white);//设置所选择行的背景色
		// friends.setSelectionForeground (Color.red);//设置所选择行的前景色
		// friends.setGridColor (Color.black);//设置网格线的颜色
		// friends.selectAll ();//选择所有行
		// friends.setRowSelectionInterval (0,2);//设置初始的选择行,这里是1到3行都处于选择状态
		// friends.clearSelection ();//取消选择
		// friends.setDragEnabled (false);//不懂这个
		// friends.setShowGrid (false);//是否显示网格线
		// friends.setShowHorizontalLines (false);//是否显示水平的网格线
		// friends.setShowVerticalLines (true);//是否显示垂直的网格线
		// friends.setValueAt ("tt", 0, 0);//设置某个单元格的值,这个值是一个对象
		// friends.doLayout ();
		// friends.setBackground (Color.lightGray);

		
		// jTable.setModel(t);

		// this.mainPanel.add(jTable);
		jViewport.add(jTable);
		parentFrame.validate();

		// panel.repaint();
		// this.parentFrame.validate();

	}*/
	
	
	
	public void getTableValue(){
		List<Map<String,Object>> data = ((SimplePropTableModel)table.getModel()).getTableData();
		for(Map<String,Object> row :data){
			String columnName = (String)row.get("name");
			String columnCnName = (String) row.get("cnName");
			boolean isQuery = (Boolean)row.get("isQuery");
			boolean isTable = (Boolean)row.get("isTable");
			boolean isEdit = (Boolean)row.get("isEdit");
			
			String validateTypeName1 = (String) row.get("validateType1"); 
			String validateRule1 = null;
//					(String) row.get("validateRule1");
			/*String validateTypeName2 = (String) row.get("validateType2"); 
			String validateRule2 = (String) row.get("validateRule2");*/
			//String validateTypeName3 = (String) row.get("validateType3"); 
			//String validateRule3 = (String) row.get("validateRule3");
			String editType=(String)row.get("editType");
			
			for(ColumnClazz col:this.tableClazz.getColumns()){
				if(col.getPropName().equals(columnName)){
					col.setPropCnName(columnCnName);
					col.setQueryCol(isQuery);
					col.setTableCol(isTable);
					col.setEditCol(isEdit);
					
					col.clearRule();//清空规则
					//校验规则
					ValidateRule rule = buildValidateRule(validateTypeName1, validateRule1); 
					if(rule!=null)col.addValidateRule(rule);
					/*ValidateRule rule2 = buildValidateRule(validateTypeName2, validateRule2); 
					if(rule2!=null)col.addValidateRule(rule2);*/
					
					if(editType!=null){
						PropEditor e = buildEditor(editType, null);
						col.setPropEditor(e);
					}
					
					//ValidateRule rule3 = buildValidateRule(validateTypeName3, validateRule3); 
					//if(rule3!=null)col.addValidateRule(rule3);
				}
			}
			
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// btnGener.setEnabled(false);
		if(e.getActionCommand().indexOf("加载")!=-1){
			String moduleName = txtModule.getText();
			String tableName = txtTable.getText();

			reloadColumnPanel2();
		
		}else if(e.getActionCommand().equals("生成树形界面")){
			getTableValue();
			doGenerAction(true);
		}else{//取值并生成
			/*Vector<Vector> data =  ((DefaultTableModel)table.getModel()).getDataVector();
			
			
			for(int i = 0;i<data.size();i++){
				Vector rowdata =data.get(i);
				
				String columnName = (String) rowdata.get(1);
				String columnCnName = (String) rowdata.get(2);
				String isQuery = (String)rowdata.get(3);
				String isTable = (String)rowdata.get(4);
				String isEdit = (String)rowdata.get(5);
				String isHidden = (String)rowdata.get(6);
				
				//校验规则
				String isRequired = (String)rowdata.get(7);
				String strSize = (String)rowdata.get(8);
				
				
				for(ColumnClazz col:this.tableClazz.getColumns()){
					if(col.getPropName().equals(columnName)){
						col.setPropCnName(columnCnName);
						col.setQueryCol(GenerUtil.getBool(isQuery));
						col.setTableCol(GenerUtil.getBool(isTable));
						col.setEditCol(GenerUtil.getBool(isEdit));
						col.setHiddenEditCol(GenerUtil.getBool(isHidden));
						
						col.clearRule();//清空规则
						//校验规则
						if(GenerUtil.getBool(isRequired)){
							ValidateRule required =  new ValidateRule(ValidateType.REQUIRED);
							col.addValidateRule(required);
						}
						if(!"".equals(strSize.trim())){
							String[] sizes = strSize.split(",");
							ValidateRule size = new ValidateRule(ValidateType.LENGTH);
							if(sizes.length>1){
								size.setMinSize(sizes[0]);
								size.setMaxSize(sizes[1]);						
							}else{
								size.setMaxSize(sizes[0]);
							}
							col.addValidateRule(size);
						}
						
						break;
					}
				}
			}
			doGenerAction();*/
			getTableValue();
			doGenerAction(false);
		}
	}
	
	public void doGenerAction(boolean tree){
		try {
			String tableName = txtTable.getText();
			String moduleName = txtModule.getText();
			moduleName = GenerUtil.generModuleName(moduleName, tableName);
			String modelType= (String) this.entityType.getSelectedItem();
			boolean pageable = this.chkPageable.isSelected();
			//参数准备
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("modelType", modelType);
			params.put("pageable",pageable);
			
			//1 生成
			if(this.tableClazz==null){
				this.tableClazz = new TableClazz(tableName);
			}
			//1 实体生成
			//1生成实体
			EntityGenerator eg = new EntityGenerator(moduleName);
			EntityTable table = new EntityTable(tableName);	//参数为 表名：tc_pick_after,子表对象：sub
			table.setIdGenerType("uuid");
			eg.generatorModel(table,tableClazz,modelType);
			
			//2 java代码生成
			ServiceDaoGenerator seg = new ServiceDaoGenerator(moduleName);
			seg.generator(tableClazz,params);
			ActionGenerator ag = new ActionGenerator(moduleName);
			ag.generator(tableClazz, params);
			
			//3 mxml代码生成
			FlexGenerator fg = new FlexGenerator(moduleName);
			fg.generator(tableClazz, params);
			
			//打开文件夹
			Runtime.getRuntime().exec("cmd.exe /c start "+ GeneratorProperties.getRequiredProperty("outRoot"));
		} catch (Exception ee) {
			ee.printStackTrace();
			// JOptionPane.showMessageDialog(parentFrame,
			// "生成代码报错："+ee.getMessage());
			// btnGener.setEnabled(true);
			return;
		}
	}
}